<template>
  <div class="CostFirstTrial">
    <group label-width="1rem" label-align="left" gutter="0">
      <cell>
        <span slot="title">报销人</span>
        <span slot="after-title">{{nickName}}</span>
        <!--<span slot="after-title" style="margin-left: 5px">部门</span>-->
        <span slot="after-title" style="margin-left: 20px">{{departmentName}}</span>
        <span slot="child" class="titleChild">{{_dateFormat(createdTime)}}</span>
      </cell>
      <cell is-link @click.native="gotoWorkOrderDetail()">
        <span slot="title">工单编号</span>
        <span slot="after-title">{{workOrderCode}}</span>
      </cell>
      <cell v-if="requestCode" is-link @click.native="gotoRequestDetail()">
        <span slot="title">申请单号</span>
        <span slot="after-title">{{requestCode}}</span>
      </cell>
      <cell>
        <span slot="title">报销单号</span>
        <span slot="after-title">{{code}}</span>
      </cell>
    </group>
    <flexbox style="background-color:#fff">
      <flexbox-item style="flex: 0 0 80px;overflow: auto" :class="itemAnimate">
        <div class="imgBox">
          <img v-if="formFileStore.path" :src="_getPath(formFileStore.path)" alt="" class="previewer-img"
               @click="show(0)">
        </div>
      </flexbox-item>
      <flexbox-item ref="itemHeight" :class="itemAnimate" class="flex-table">
        <x-table :cell-bordered="false" :content-bordered="false">
          <thead>
          <tr>
            <th style="width: 25%">费用科目</th>
            <th style="width: 25%">初审金额</th>
            <th style="width: 25%">填报金额</th>
            <th style="width: 25%">差额</th>
          </tr>
          </thead>
          <tbody>
          <tr class="colorBlue" v-for="(item,index) in costList" :key="index">
            <td :title="item.subjectName||''" class="overflowHide">{{item.subjectName||""}}</td>
            <td>{{item.firstFigure||0}}</td>
            <td>{{item.showBeforeFigure?item.fillFigure:0}}</td>
            <td>{{item.showBeforeFigure?(item.firstFigure - item.fillFigure):0}}</td>
          </tr>
          <tr>
            <td>合计</td>
            <td>{{firstFigure}}</td>
            <td>{{fillFigure}}</td>
            <td style="color: #99232a">{{firstFigure - fillFigure}}</td>
          </tr>
          </tbody>
        </x-table>
      </flexbox-item>
    </flexbox>

    <tab active-color="#43A2FE" style="margin-top: 10px" v-model="currentIndex">
      <tab-item v-for="(item, index) in costList" :key="index" :selected="index===currentIndex">
        <span>明细{{index+1}}</span>
      </tab-item>
    </tab>
    <swiper ref="swiper" :threshold="10000" :min-moving-distance="10000" v-model="currentIndex" :show-dots="false" @on-index-change="setHeight">
      <swiper-item v-for="(item, index) in costList" :key="index">
        <CostDetail v-if="index==currentIndex" firstOrSecond="1" ref="swiper_item" :formdata="item"></CostDetail>
      </swiper-item>
    </swiper>
    <group label-width="1rem" label-align="left">
      <x-textarea title="审批意见" v-model="firstOption" :max="140" placeholder="请输入">
      </x-textarea>
    </group>
    <flexbox style="margin-top: 10px" v-if="currentIndex == (costList.length-1)">
      <flexbox-item>
        <x-button type="warn" @click.native="approval(false)">驳回</x-button>
      </flexbox-item>
      <flexbox-item style="margin-left: 0">
        <x-button type="primary" @click.native="approval(true)">通过</x-button>
      </flexbox-item>
    </flexbox>
    <div v-transfer-dom>
      <previewer :list="bigImgPath" ref="previewer" :options="options"></previewer>
    </div>
  </div>
</template>

<script>
  import {
    Group,
    Cell,
    CellBox,
    XInput,
    XTable,
    Flexbox,
    FlexboxItem,
    Tab,
    TabItem,
    Swiper,
    SwiperItem,
    Selector,
    XButton,
    XTextarea,
    TransferDom,
    XDialog,
    Previewer,
  } from 'vux'
  import CostDetail from './costDetail.vue'

  export default {
    name: "CostFirstTrial",
    components: {
      Group,
      Cell,
      CellBox,
      XInput,
      XTable,
      Flexbox,
      FlexboxItem,
      Tab,
      TabItem,
      Swiper,
      SwiperItem,
      CostDetail,
      Selector,
      XButton,
      XTextarea,
      XDialog,
      Previewer,
    },
    directives: {
      TransferDom
    },
    data() {
      return {
        nickName: '',//报销人
        departmentName: '',//部门
        createdTime: '',//创建时间
        workOrderCode: '',//工单编号
        code: '',//报销单号
        requestCode: '',//申请单号
        costList: [],//费用列表
        currentIndex: 0,//当前费用明细
        firstOption: '',//审批意见
        showBigPicture: false,//大图显示
        formFileStore: {},
        //图片数组
        bigImgPath: [],
        //图片预览
        options: {
          getThumbBoundsFn(index) {
            let thumbnail = document.querySelectorAll('.CostFirstTrial .previewer-img')[index]
            let pageYScroll = window.pageYOffset || document.documentElement.scrollTop
            let rect = thumbnail.getBoundingClientRect()
            return {x: rect.left, y: rect.top + pageYScroll, w: rect.width}

          }
        },
        itemAnimate: "",
      }
    },
    mounted() {
      if (this.$route.query.id) {
        this.$http.get('/expense/api/expenseForm/' + this.$route.query.id).then(res => {
            // 格式化后端数据至前端
            let object = res.data.data;
            this.id = object.id;
            this.workOrderCode = object.workOrderCode;
            this.code = object.code;
            //判断工单对应的申请单
            this.$http.get('/expense/api/RequestForm', {
              params: {
                workOrderCode: object.workOrderCode,
                noPage: true,
              }
            }).then(resp => {
                if (resp.data.data.length > 0) {
                  this.requestCode = resp.data.data[0].code;
                  this.requestId = resp.data.data[0].id;
                }
              }
            );
            this.createdTime = object.createdTime;
            this.nickName = object.expenseUser && object.expenseUser.nickName;
            this.departmentName = object.expenseUser && object.expenseUser.department && object.expenseUser.department.departmentName;
            //多数情况只会上传一张图片
            // this.formFileStore = object.formFileStorePath ? object.formFileStorePath[0] : {};
            //图片id转path
            object.formFileStore && this.$http.get('/work/api/upload/byid', {params: {ids: object.formFileStore}}).then(res => {
              this.formFileStore = res.data.data[object.formFileStore] ? res.data.data[object.formFileStore][0] : {};
              //如果有多张则在预览图中显示
              this.bigImgPath = res.data.data[object.formFileStore].map(item => {
                return {msrc:this._getPathNo(item.path), src:this._getPathNo(item.path)}
              });
            });
            let promisesAll = []
            object.expenseFormItems.forEach(item => {
              promisesAll.push(new Promise((resolveAll, rejectAll) => {
                item.subjectList = JSON.parse(item.subjectContent);
                item.firstFigure = item.firstFigure || '';
                item.showBeforeFigure = false;//控制之前对比金额的显示
                //如果没图片就不发请求了
                if (!item.invoiceFileStore && !item.voucherFileStore) {
                  item.allImgs = [];
                  resolveAll();
                  //如果有两类图片 发送两类请求
                } else if (item.invoiceFileStore && item.voucherFileStore) {
                  this.$http.all([
                    this.$http.get('/work/api/upload/byid', {params: {ids: item.invoiceFileStore}}),
                    this.$http.get('/work/api/upload/byid', {params: {ids: item.voucherFileStore}})
                  ]).then(this.$http.spread((res1, res2) => {
                    item.allImgs = res1.data.data[item.invoiceFileStore].concat(res2.data.data[item.voucherFileStore]).map(r => {
                      return {msrc:this._getPathNo(r.path), src:this._getPathNo(r.path)}
                    });
                    resolveAll();
                  }));
                  //否则有那个请求就发那个请求
                } else {
                  this.$http.get('/work/api/upload/byid', {params: {ids: item.invoiceFileStore || item.voucherFileStore}}).then(res => {
                    item.allImgs = res.data.data[item.invoiceFileStore || item.voucherFileStore].map(r => {
                      return {msrc:this._getPathNo(r.path), src: this._getPathNo(r.path)}
                    });
                    resolveAll();
                  })
                }
              }));
            });
            Promise.all(promisesAll).then(() => {
              this.costList = object.expenseFormItems;
              this.$nextTick(() => {
                switch (this.costList.length) {
                  case 0:
                  case 1:
                    this.itemAnimate = 'itemAnimate90';
                    break;
                  case 2:
                    this.itemAnimate = 'itemAnimate120';
                    break;
                  default:
                    this.itemAnimate = 'itemAnimate150';
                    break;
                }
              });
              //确定科目类别之再确定高度
              this.setHeight();
            })
          }
        )
      }
      else {
        this.setHeight()
      }
    },
    computed: {
      firstFigure() {
        return this.costList.reduce((total, item) => {
          let sum = total
          if (item.status === 1 && item.showBeforeFigure) {
            sum += parseInt(item.firstFigure || 0)
          }
          return sum
        }, 0);
      },
      fillFigure() {
        return this.costList.reduce((total, item) => {
          let sum = total;
          if (item.showBeforeFigure) {
            sum += parseInt(item.fillFigure || 0)
          }
          return sum
        }, 0);
      }
    }
    ,
    methods: {
      // 申请单界面
      gotoRequestDetail() {
        this.$router.push({path: '/expense/CostApplyTrial', query: {id: this.requestId, type: 1,auth:1}})
      },
      // 工单界面
      gotoWorkOrderDetail() {
        let params = {code: this.workOrderCode}
        this.$http.get('/work/api/workorder', {params: params}).then(res => {
            if (res.data.data.rows.length > 0)
              this.$router.push({path: '/engineer/enWorkingOrder', query: {orderId: res.data.data.rows[0].id}})
          }
        )
      },
      //提交数据
      approval(index) {
        let expenseFormItems = this.costList.map(item => {
          if (item.status != 1) {
            item.firstFigure = 0;
          }
          return {id: item.id, status: item.status, firstFigure: parseInt(item.firstFigure)}
        });
        let params = {
          expenseFormItems: expenseFormItems,
          firstAudit: {id: this.$store.state.user.userInfo.id},
          firstOption: this.firstOption,
          firstTrialAmount: this.firstFigure,
        }
        this.$vux.confirm.show({
          title: '提醒',
          content: '请检查数据是否填写完整，'+(index?'审批':'驳回')+'后无法撤回，是否确定提交？',
          onCancel: () => {

          },
          onConfirm: () => {
            this.$http.put('/expense/api/expenseForm/' + this.id + '/first?audit=' + index, params).then(res => {
              let content = '操作完成，请悉知！'
              if (res.data.data.status == 2) {
                content = '初审完成，请悉知！'
              }
              if (res.data.data.status == 4) {
                content = '驳回完成，请悉知！'
              }
              this.$vux.alert.show({
                title: '初审结果',
                content: content,
                onShow() {
                },
                onHide: () => {
                  this.$router.go(-1)
                }
              })
            });
          }
        })

      },
      //图片预览
      show(index) {
        this.$refs.previewer.show(index)
      }
      ,
      showBig() {
        this.showBigPicture = !this.showBigPicture;
      }
      ,
      //设置swapper高度
      setHeight() {
        this.$nextTick(() => {
          this.$refs.swiper.xheight = this.$refs.swiper_item[0].$el.clientHeight + 'px'
        })
      }
      ,
    }
  }
</script>

<style lang="less">
  .CostFirstTrial {
    .weui-label {
      text-align-last: justify;
      padding-right: .2rem;
    }
    .vux-label {
      text-align-last: justify;
      padding-right: .2rem;
    }
    .weui-cells{
      line-height: 1.3em;
    }
    .weui-cell {
      line-height: 1.5em;
      padding: 5px 10px;
    }
    .weui-input{
      line-height: 1.5em;
      height: 1.5em;
    }
    .titleChild {
      font-size: 13px;
      position: relative;
      bottom: -5px;
    }
    .colorBlue {
      color: #43A2FE;
    }
    .flex-table {
      overflow: auto;
      > table {
        table-layout: fixed;
      }
      .overflowHide {
        word-break: keep-all;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
    .itemAnimate90 {
      animation: move90 1.5s forwards;
    }
    @keyframes move90 {
      100% {
        height: 90px;
      }
    }
    .itemAnimate120 {
      animation: move120 1.5s forwards;
    }
    @keyframes move120 {
      100% {
        height: 120px;
      }
    }
    .itemAnimate150 {
      animation: move150 1.5s forwards;
    }
    @keyframes move150 {
      100% {
        height: 150px;
      }
    }
    .imgBox {
      width: 80px;
      height: 100%;
      padding: 10px 5px;
      text-align: center;
      > img {
        width: 70px;
      }
    }
    .vux-table {
      line-height: 30px;
      font-size: 13px;
    }
    .vux-x-textarea {
      .weui-cell__bd {
        padding: 2px;
        border: 0.01rem solid #E5E5E5;
        border-radius: 5px;
      }
    }
    .weui-cell_select .weui-cell__bd:after {
      border-color: #3FBCFC;
      right: 22px;
      border-width: 0 2px 2px 0;
    }
    .vux-flexbox {

      .vux-flexbox-item {
        border-radius: 0%;
        .weui-btn_primary {
          background: #43A2FE;
        }
        .weui-btn_warn {
          background: #E05163;
        }
        .weui-btn {
          border-radius: 0;
        }
      }
    }
  }
</style>
